package com.yisu.expressway.userprofile_setting;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.reflect.TypeToken;
import com.pizidea.imagepicker.AndroidImagePicker;
import com.pizidea.imagepicker.bean.ImageItem;
import com.will.network.images.round.CircleImageView;
import com.yisu.expressway.R;
import com.yisu.expressway.activity.BaseActivity;
import com.yisu.expressway.application.ExApplication;
import com.yisu.expressway.login.LoginManager;
import com.yisu.expressway.model.UserProfile;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.ui.MultiButtonDialog;
import com.yisu.expressway.utils.BitmapUtil;
import com.yisu.expressway.utils.QiniuUploadManager;
import com.yisu.expressway.utils.StringUtil;
import com.yisu.expressway.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;

public class UserProfileSetting extends BaseActivity {

    @Bind(R.id.tv_nick_name)
    protected TextView mTv_NickName;
    @Bind(R.id.tv_phone)
    protected TextView mTv_phone;
    @Bind(R.id.iv_avatar)
    protected CircleImageView mIv_avatar;

    String profileKey = "";
    String profileValue = "";
    TextView targetPrifleView = null;
    UserProfile user;

    private final static String PROFILE_USERNAME = "userName";
    private final static String PROFILE_PHONE = "contactPhone";
    private final static String PROFILE_AVATAR = "avatarUrl";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_profile_setting);
        setTitle(R.string.profile_edit);
        initView();
    }

    private void initView(){

        user = LoginManager.getUser();
        if(user != null) {
            mTv_NickName.setText(user.userName);
            mTv_phone.setText(user.contactPhone);
            Glide.with(ExApplication.getInstance().getApplicationContext())
                    .load(user.avatarUrl)
                    .asBitmap()
                    .placeholder(R.drawable.ic_default_avatar)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .centerCrop()
                    .into(mIv_avatar);
        }

    }

    @OnClick(R.id.iv_avatar)
    protected void onClickAvatar(){
        AndroidImagePicker.getInstance().pickSingle(UserProfileSetting.this, true, new AndroidImagePicker.OnImagePickCompleteListener() {
            @Override
            public void onImagePickComplete(List<ImageItem> items) {
                if(items != null && items.size() > 0){
                    final String imgPath = items.get(0).path;
                    String filePath = BitmapUtil.scalePictureBitmapForAvatar(imgPath);//压缩图片
                    if (StringUtil.isNullOrEmpty(filePath)) {
                        filePath = imgPath;
                    }

                    showLoading();

                    QiniuUploadManager.getInstance().getTokenAndUploadHeadImg(filePath, new QiniuUploadManager.UpLoadListener() {
                        @Override
                        public void uploadSuccess(String url, int w, int h) {
                            dismissLoading();
                            profileKey = PROFILE_AVATAR;
                            profileValue = url;
                            postNewProfile(null);

                            Bitmap localImg = getLoacalBitmap(imgPath);
                            if(localImg != null){
                                mIv_avatar.setImageBitmap(localImg);
                            }

                        }

                        @Override
                        public void uploadFail(String error) {
                            ToastUtil.displayShortToastMsg(UserProfileSetting.this, TextUtils.isEmpty(error) ? "上传失败" : error);
                            dismissLoading();
                        }

                        @Override
                        public void onGetToken(String token) {

                        }

                        @Override
                        public void onGetTokenApiFail(String error) {
                            ToastUtil.displayLongToastMsg(UserProfileSetting.this, error);
                            dismissLoading();
                        }

                        @Override
                        public void onGetTokenNetworkFail(VolleyError volleyError) {
                            ToastUtil.displayShortToastMsg(UserProfileSetting.this, "网络不给力");
                            dismissLoading();
                        }
                    });

                }else {
                    ToastUtil.displayShortToastMsg(UserProfileSetting.this,"选取图片失败");
                }
            }
        });
    }



    @OnClick({R.id.nick_name_root,R.id.bind_phone_root})
    protected void editProfileClick(RelativeLayout view){
        int titleId = -1;
        profileKey = "";
        profileValue = "";
        targetPrifleView = null;

        switch (view.getId()){
            case R.id.nick_name_root:
                profileKey = PROFILE_USERNAME;
                titleId = R.string.nick_name;
                targetPrifleView = mTv_NickName;
                break;
            case R.id.bind_phone_root:
                profileKey = PROFILE_PHONE;
                titleId = R.string.bind_cellphone;
                targetPrifleView = mTv_phone;
                break;
            default:
                break;
        }

        if(titleId != -1){
            final MultiButtonDialog dialog = new MultiButtonDialog(this,true);
            dialog.show();
            dialog.setDialogTitle(titleId);
            dialog.setContentText(targetPrifleView.getText().toString());
            dialog.setPositiveClickListener(new MultiButtonDialog.PositiveClickListener() {
                @Override
                public void onPositiveClick(String inputContent) {
                    profileValue = inputContent;
                    dialog.dismiss();
                    postNewProfile(targetPrifleView);
                }
            });
        }
    }

    private void postNewProfile(final TextView targetView){

        Map<String, Object> params = new HashMap();
        params.put(profileKey, profileValue);

        ApiClientHelper.postApi(ApiSetting.modifyUserProfile(), new TypeToken<Object>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<Object>>() {
            @Override
            public void onResponse(ApiResult<Object> result) {
                if (!result.success) {
                    ToastUtil.displayLongToastMsg(UserProfileSetting.this, result.getMsg());
                    return;
                }

                ToastUtil.displayShortToastMsg(UserProfileSetting.this, R.string.modify_success);
                if(targetView != null){
                    targetView.setText(profileValue);
                }

                UserProfile user = LoginManager.getUser();
                if(profileKey.equals(PROFILE_USERNAME)){
                    user.setUserName(profileValue);
                }else if(profileKey.equals(PROFILE_PHONE)){
                    user.setContactPhone(profileValue);
                }else if(profileKey.equals(PROFILE_AVATAR)){
                    user.setAvatarUrl(profileValue);
                }

                LoginManager.onLoginSuccess(user);

                EventBus.getDefault().post(new UpdateProfileEvent(true));

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtil.displayShortToastMsg(UserProfileSetting.this, volleyError.getMessage());
            }
        }, this);
    }

    /**
     * 加载本地图片
     * http://bbs.3gstdy.com
     * @param url
     * @return
     */
    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
}
